const crypto = require('crypto');

/**
 * 生成消息ID
 * @returns {string} 消息ID
 */
function generateMid() {
    return "" + Math.floor(1000 * Math.random()) + new Date().getTime() + " 0";
}

/**
 * 生成UUID
 * @returns {string} UUID
 */
function generateUuid() {
    return "-" + Date.now() + Math.random().toString(36).substr(2, 9);
}

/**
 * 生成设备ID
 * @param {string} userId 用户ID
 * @returns {string} 设备ID
 */
function generateDeviceId(userId) {
    const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
    const uuid = [];
    
    for (let i = 0; i < 36; i++) {
        if (i === 8 || i === 13 || i === 18 || i === 23) {
            uuid[i] = "-";
        } else if (i === 14) {
            uuid[i] = "4";
        } else {
            const random = Math.floor(16 * Math.random());
            uuid[i] = chars[i === 19 ? (3 & random) | 8 : random];
        }
    }
    
    return uuid.join("") + "-" + userId;
}

/**
 * 生成签名
 * @param {string} t 时间戳
 * @param {string} token 令牌
 * @param {string} data 数据
 * @returns {string} 签名
 */
function generateSign(t, token, data) {
    const j = t;
    const h = 34839810;
    const msg = token + "&" + j + "&" + h + "&" + data;
    const md5 = crypto.createHash('md5');
    md5.update(msg);
    return md5.digest('hex');
}

/**
 * 转换Cookie字符串为对象
 * @param {string} cookiesStr Cookie字符串
 * @returns {Object} Cookie对象
 */
function transCookies(cookiesStr) {
    const cookies = {};
    const cookiePairs = cookiesStr.split("; ");
    
    for (const pair of cookiePairs) {
        try {
            const [key, ...valueParts] = pair.split('=');
            cookies[key] = valueParts.join('=');
        } catch (error) {
            continue;
        }
    }
    
    return cookies;
}

/**
 * 解密消息数据
 * @param {string} data 加密数据
 * @returns {Object} 解密后的数据
 */
function decrypt(data) {
    try {
        // 这里需要实现具体的解密逻辑
        // 暂时返回原始数据，后续根据闲鱼的具体加密方式实现
        return {
            success: true,
            data: data,
            message: "解密功能待实现"
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

module.exports = {
    generateMid,
    generateUuid,
    generateDeviceId,
    generateSign,
    transCookies,
    decrypt
};
